// ============================== 生成路由菜单 =============================

// 引用文件
import {
  asyncRoutes,
  constantRoutes
} from '@/router';
import {
  UserRoleTreeMenuList
} from "../../api/menu";
import Layout from '@/layout';
import Cookies from 'js-cookie';

/**
 * 遍历生成树形菜单
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];                         // 生成好的菜单数组

  routes.forEach(route => {
    const tmp = Object.assign({
      children: []
    }, {
      ...route
    })

    // 如果当前数据包含子级菜单数据时则对子级菜单进行遍历
    if (tmp.children) {
      tmp.children = filterAsyncSonRoutes(tmp.children, tmp.id);
    }

    if (localStorage.getItem('language') === 'en_US') {
      tmp.title = tmp.name;
    }

    // 如果当前数据的 parentId 为 0 则添加为一级菜单；否则添加为二级菜单
    if (tmp.parentId === "0") {
      try {
        if (tmp.alwaysShow == "true") {
          res.push({
            id: tmp.id,                                       // 路由ID
            path: tmp.path,                                   // 路由页面地址
            component: Layout,                                // 依赖组件，用于在Layout内显示页面
            name: tmp.name,                                   // 路由名称
            meta: {                                           // 路由配置属性
              title: tmp.title,                               // 菜单标题文本
              icon: tmp.icon,                                 // 菜单图标
            },
            alwaysShow: tmp.alwaysShow == "true",             // 如果一级页面中只有一个二级页面则不显示一级页面问题
            children: tmp.children                            // 子级路由菜单
          });
        } else {
          let childrenData = tmp.children.find(item => item.name === tmp.redirect);
          // console.log(tmp);
          // console.log(childrenData);
          res.push({
            id: tmp.id,                                       // 路由ID
            path: "/",                                        // 路由页面地址
            component: Layout,                                // 依赖组件，用于在Layout内显示页面
            redirect: tmp.redirect,
            children: [
              {
                path: childrenData.path,
                component: childrenData.component,
                name: tmp.name,
                meta: {
                  title: tmp.title,
                  icon: tmp.icon,
                  affix: true,
                },
              },
              ...tmp.children
            ]
          });
        }
      } catch (ex) {
        console.log(ex);
      }
    } else {
      // 如果当前循环节点有值时进行菜单数据生成
      if (tmp.children) {
        tmp.children.forEach(item => {
          try {
            res.push({
              id: tmp.id,                                 // 路由ID
              path: `/${item.path}`,
              component: require(`@/views/${item.component}`).default,
              name: item.name,
              meta: {                                    // 路由配置属性
                title: item.title,                       // 菜单标题文本
                icon: item.icon,                         // 菜单图标
              },
            });
          } catch (ex) {
            console.log(ex);
          }
        });
      }
    }
  })
  //console.log(res)
  return res;
}

/**
 * 遍历生成二级菜单
 * @param routes 一级菜单的子级list
 * @param parentId 所属菜单ID
 */
export function filterAsyncSonRoutes(routes, parentId) {
  const res = []; // 生成好的菜单数组
  routes.forEach(route => {
    var tmp = Object.assign({
      children: []
    }, {
      ...route
    })
    if (localStorage.getItem('language') === 'en_US') {
      tmp.title = tmp.name;
    }
    if (tmp.parentId === parentId) {
      try {
        res.push({
          path: tmp.path,
          component: require(`@/views/${tmp.component}`).default,
          name: tmp.name,
          meta: {
            title: tmp.title,
            icon: tmp.icon,
          },
          hidden: tmp.hidden === "true", // 是否隐藏菜单项  true:隐藏  false:不隐藏
        });
      } catch (ex) {
        console.log(ex);
      }
    }
    //console.log(res);
  });
  return res;
}

const state = {
  routes: [],
  addRoutes: [],
  btnList: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_BUTTONLIST: (state, list) => {
    state.btnList = list
  },
}

const actions = {
  // 获取菜单权限
  generateRoutes({commit}, roles) {
    return new Promise(resolve => {
      let accessedRoutes;

      UserRoleTreeMenuList().then(response => {
        const {data} = response;

        // 将数据源存至临时缓存
        localStorage.setItem('ALL_USERMENU', JSON.stringify(data));

        accessedRoutes = filterAsyncRoutes(data, roles);

        // console.log(asyncRoutes);
        // console.log(accessedRoutes);

        commit('SET_ROUTES', accessedRoutes);
        resolve(accessedRoutes);
      })

      // // 走本地菜单
      // const accessedRoutes = asyncRoutes || []
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)
    })
  },
  // 获取按钮权限
  setButtonList({commit}, list) {
    commit('SET_BUTTONLIST', list)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
